package com.ssyc.gsk_teacher.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ssyc.common.base.Constants;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.PickerManager;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.DateUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.activity.TeacherAttendanceDetailsActivity;
import com.ssyc.gsk_teacher.adapter.StudentAnalyRvAdapter;
import com.ssyc.gsk_teacher.bean.StudentAnalyInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生分析
 * Created by Administrator on 2018/7/2 0002.
 */

public class TeacherStudentAnalyFragment extends LazyBaseFragment implements StudentAnalyRvAdapter.onDetailsClickListener {

    //下拉刷新
    private SmartRefreshLayout srf;

    //列表控件
    private RecyclerView rv;

    //加载视图
    private RelativeLayout rlLoading;

    //内容布局
    private RelativeLayout rlContent;


    //数据集合
    private List<StudentAnalyInfo.DataBean> oldDatas;

    //适配器
    private StudentAnalyRvAdapter adapter;

    //空视图
    private View emptyView;

    //班级号
    private String classNum;

    //头布局
    private View headView;

    //选择的开始时间和结束
    private String begindate, enddate;

    public static final String TAG = TeacherStudentAnalyFragment.class.getName();
    private TextView tvBeginTime;
    private TextView tvEndTime;

    //单体模式
    private static class LazyHolder {
        private static final TeacherStudentAnalyFragment INSTANCE = new TeacherStudentAnalyFragment();
    }

    public static final TeacherStudentAnalyFragment newInstance(String classNum) {
        TeacherStudentAnalyFragment teacherStudentAnalyFragment = TeacherStudentAnalyFragment.LazyHolder.INSTANCE;
        Bundle bundle = new Bundle();
        bundle.putString("classnum", classNum);
        teacherStudentAnalyFragment.setArguments(bundle);
        return teacherStudentAnalyFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.teacher_fragment_student_analy;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        showContent();

        //初始化视图
        initView(view);

        //获取班级号
        initIntent();

        //初始化下拉刷新控件
        initSrf();

        //计算初次进入的默认日期
        initTime();

        //初始化列表控件
        initRv();

        //请求服务器
        http(BqaManager.NORML);
    }


    /**
     * 初始化视图
     */
    private void initView(View view) {
        srf = view.findViewById(R.id.srf);
        rv = view.findViewById(R.id.rv);
        rlLoading = view.findViewById(R.id.rl_loading);
        rlLoading.setVisibility(View.VISIBLE);
        rlContent = view.findViewById(R.id.rl_content);
    }

    /**
     * 获取班级号
     */
    private void initIntent() {
        classNum = getArguments().getString("classnum");
    }


    /**
     * 初始化开始时间和结束时间.默认开始时间为当前月份的前一个
     */
    private void initTime() {
        enddate = DateUtils.getTime(new Date(), "yyyy-MM-dd");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        begindate = format.format(m);
    }


    /**
     * 初始化下拉刷新控件
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, null);
    }

    /**
     * 初始化列表控件
     */
    private void initRv() {
        headView = View.inflate(getContext(), R.layout.teacher_headview_analy, null);
        tvBeginTime = headView.findViewById(R.id.tv_begin_time);
        tvEndTime = headView.findViewById(R.id.tv_end_time);
        //设置初始时间
        tvBeginTime.setText(begindate);
        tvEndTime.setText(enddate);
        tvBeginTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePicker(0);
            }
        });

        tvEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePicker(1);
            }
        });
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(getContext(), R.layout.base_rv_common_empty_view, null);
        TextView tvMsg = emptyView.findViewById(R.id.tv_content);
        tvMsg.setText("该班级暂无学生数据");
        adapter = new StudentAnalyRvAdapter(getContext(), R.layout.teacher_rv_student_analy, oldDatas);
        adapter.setListener(this);
        adapter.addHeaderView(headView);
    }

    /**
     * @param pos
     */
    private void showTimePicker(int pos) {
        PickerManager.showPickerByYeaerAndMonthAndDayByLimit(getContext(), new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (pos == 0) {

                    String chooseBeginDate = DateUtils.getTime(date, "yyyy-MM-dd");

                    //比较时间差,然后刷新页面数据
                    long end = DateUtils.getTime(enddate, "yyyy-MM-dd");
                    long start = DateUtils.getTime(chooseBeginDate, "yyyy-MM-dd");

                    //计算选择的开始和结束时间,转化为date格式
                    Date startDate = null;
                    Date endDate = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    try {
                        startDate = sdf.parse(chooseBeginDate);
                        endDate = sdf.parse(enddate);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (end <= start) {
                        UiUtils.Toast("选择的结束时间不能小于开始时间", false);
                        return;
                    } else if (DateUtils.getDiffMonth(startDate, endDate) < 1) {
                        //小于1个月
                        UiUtils.Toast("选择的时间间隔不能小于1个月", false);
                        return;
                    } else if (DateUtils.getDiffMonth(startDate, endDate) > 6) {
                        //大于6个月
                        UiUtils.Toast("选择的时间间隔不能超过6个月", false);
                        return;
                    } else {

                        begindate = DateUtils.getTime(date, "yyyy-MM-dd");

                        tvBeginTime.setText(begindate);

                        //刷新数据
                        http(BqaManager.PULLREFRESH);
                    }
                } else if (pos == 1) {

                    String chooseEndDate = DateUtils.getTime(date, "yyyy-MM-dd");

                    //比较时间差,然后刷新页面数据
                    long end = DateUtils.getTime(chooseEndDate, "yyyy-MM-dd");
                    long start = DateUtils.getTime(begindate, "yyyy-MM-dd");

                    //计算选择的开始和结束时间,转化为date格式
                    Date startDate = null;
                    Date endDate = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    try {
                        startDate = sdf.parse(begindate);
                        endDate = sdf.parse(chooseEndDate);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (end <= start) {
                        UiUtils.Toast("选择的结束时间不能小于开始时间", false);
                    } else if (DateUtils.getDiffMonth(startDate, endDate) < 1) {
                        //小于1个月
                        UiUtils.Toast("选择的时间间隔不能小于1个月", false);
                        return;
                    } else if (DateUtils.getDiffMonth(startDate, endDate) > 6) {
                        //大于6个月
                        UiUtils.Toast("选择的时间间隔不能超过6个月", false);
                        return;
                    } else {
                        enddate = DateUtils.getTime(date, "yyyy-MM-dd");
                        tvEndTime.setText(enddate);
                        //刷新数据
                        http(BqaManager.PULLREFRESH);
                    }
                }

            }
        });
    }

    /**
     * 请求服务器获取数据
     *
     * @param method
     */
    private void http(int method) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "6");
        map.put("acc", AccountUtils.getAccount(getContext()));
        map.put("role", AccountUtils.getRole(getContext()));
        map.put("classnum", classNum);
        map.put("begindate", begindate);
        map.put("enddate", enddate);
        map.put("apptoken", AccountUtils.getToken(getContext()));
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.STUDENTANALY, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoading, srf, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }
                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {
                    StudentAnalyInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, StudentAnalyInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            List<StudentAnalyInfo.DataBean> newDatas = info.getData();
                            if (newDatas != null) {
                                if (method == BqaManager.NORML) {
                                    oldDatas.clear();
                                    oldDatas.addAll(newDatas);
                                    BqaManager.setRv(emptyView, getContext(), adapter, rv);
                                } else {
                                    //更新数据
                                    BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                                    adapter.setEnableLoadMore(false);
                                }
                            }

                        } else {
                            UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.ERROR);
                }
            }
        });
    }


    /**
     * 点击详情的点击事件
     *
     * @param item
     */
    @Override
    public void onDetailsClick(StudentAnalyInfo.DataBean item) {
        Intent intent = new Intent(getContext(), TeacherAttendanceDetailsActivity.class);
        intent.putExtra("data", item);
        intent.putExtra("begindate", begindate);
        intent.putExtra("enddate", enddate);
        startActivity(intent);
    }

}
